package com.lzs.adx.web.modules.job.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.lzs.adx.web.modules.adx.dto.AccountDTO;
import com.lzs.adx.web.modules.adx.dto.OcpxAccountDTO;
import com.lzs.adx.web.modules.adx.dto.ReportUrlDTO;
import com.lzs.adx.web.modules.adx.service.AccountService;
import com.lzs.adx.web.modules.adx.service.OcpxAccountService;
import com.lzs.adx.web.modules.adx.service.ReportUrlService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 多监测自动填充任务
 */
@Component
@Slf4j
public class OcpxMuiltReportUrlAutoFillTask implements ITask{

    @Autowired
    private OcpxAccountService accountService;

    @Autowired
    private ReportUrlService reportUrlService;

    @Override
    public void run(String params) {
        //1.扫描限量中的+支持多监测的账户
        Map<String,Object> paramsMap=new HashMap<>();
        paramsMap.put("status","3");
        paramsMap.put("muiltReportInd",2);
        //查询限量中，开启了多监测的账号
        List<OcpxAccountDTO> list = accountService.list(paramsMap);

        if(CollectionUtil.isEmpty(list)){
            return;
        }
        //2.查询账户下所有的监测地址
        for (OcpxAccountDTO accountDTO : list) {
            String dspReportUrl = accountDTO.getReportUrl();
            String md5Current = SecureUtil.md5(dspReportUrl);

            Map<String,Object> ssMap=new HashMap<>();
            ssMap.put("dspId",accountDTO.getId());
            List<ReportUrlDTO> list1 = reportUrlService.list(ssMap);
            if(CollectionUtil.isEmpty(list1)){
                //跳过
                continue;
            }

            Map<String, ReportUrlDTO> md5Map = list1.stream().collect(Collectors.toMap(ReportUrlDTO::getUrlMd5, Function.identity()));
            Map<Integer, String> collect = list1.stream().collect(Collectors.toMap(ReportUrlDTO::getSort, ReportUrlDTO::getDspReportUrl));
            ReportUrlDTO lasterReportUrlDTO = list1.stream().max((o1, o2) -> o1.getSort() - o2.getSort()).get();

            ReportUrlDTO reportUrlDTO1 = md5Map.get(md5Current);
            //当前监测地址是最后一个
            if(reportUrlDTO1.getSort().equals(lasterReportUrlDTO.getSort())){
                log.info("当前监测最后一个不做处理了");
                continue;
            }
            //获取下一个监测地址
            String nextMd5 = collect.get(reportUrlDTO1.getSort() + 1);

            //状态开起来
            accountDTO.setStatus("1");
            accountDTO.setReportUrl(nextMd5);
            //更新监测地址
            accountService.update(accountDTO);

            HttpUtil.get("https://lhpapi.weijingrui.com/common/sysnCacheToDb");
        }

    }
}
